package com.itheima.web.manager;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import com.itheima.web.interceptor.AdminHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private AdminService adminService;

    /**
     * 生成验证码
     * @param uuid
     * @return
     */
    public LineCaptcha createImgCode(String uuid) {
        //生成图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 100);

        //获得验证码
        String code = lineCaptcha.getCode();
        System.out.println(code);
        //将验证码放入缓存中 以便于校验验证码
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE +  uuid , code  , Duration.ofMinutes(5)); //5分钟过期
        return lineCaptcha;
    }

    /**
     * 用户登录
     */
    public String login(String username, String password, String verificationCode, String uuid) {
        //1.比对验证码 ，如果失败，直接返回
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        if (!StrUtil.equals(verificationCode, redisCode)) {
            throw new BusinessException("验证码错误");
        }

        //2.根据用户名查询账户，如果失败，直接返回
        Admin admin = adminService.findByUsername(username);
        if (admin == null) {
            throw new BusinessException("当前用户名不存在");
        }
        //3.比对密码，如果失败，直接返回
        String passwordWithMd5 = SecureUtil.md5(password);//先对前端传入的密码使用md5进行加密
        if (!StrUtil.equals(passwordWithMd5, admin.getPassword())) {
            throw new BusinessException("密码有误");
        }
        //4.用户登录成功
        //4.1删除redis中验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);
        //4.2创建token
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("id", admin.getId() + "");
        tokenMap.put("username", admin.getUsername());
        String token = JwtUtil.createToken(tokenMap);

        //4.3将token存入redis中（设置有效期）
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, "1", Duration.ofHours(1));

        //4.4返回token
        return token;
    }

    /**
     *  校验用户的登录状态
     */
    public Map<String, String> profile(String token) {
      /*  //1.获取redis中的token
        Boolean flag = stringRedisTemplate.hasKey(ConstantUtil.ADMIN_TOKEN + token);
        if (!flag) {
            throw new BusinessException("登录状态异常");
        }
        //2.解析
        Map<String, String> map = JwtUtil.parseToken(token);
        String username = map.get("username");*/

        Admin tokenAdmin = AdminHolder.get();
        //3.根据username查询数据
        Admin admin = adminService.findByUsername(tokenAdmin.getUsername());
        //4.构建返回值
        Map returnMap = new HashMap();
        returnMap.put("uid", admin.getId());
        returnMap.put("username", admin.getUsername());
        returnMap.put("avatar", admin.getAvatar());


        return returnMap;
    }

    /**
     * 用户登出
     */
    public Map logout(String token) {
        //删除redis的缓存状态
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
        return null;
    }
}


